package com.google.code.motoo.codec.http;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.google.code.motoo.codec.ProtocolEncoder;
import com.google.code.motoo.codec.ProtocolEncoderOutput;
import com.google.code.motoo.codec.textline.LineDelimiter;
import com.google.code.motoo.core.IoBuffer;
import com.google.code.motoo.core.IoSession;

/**
 * 
 * HTTP/1.1 200 OK
 * Content-Length: 3059
 * Server: GWS/2.0
 * Date: Sat, 11 Jan 2003 02:44:04 GMT
 * Content-Type: text/html
 * Cache-control: private
 * Connection: keep-alive
 * 
 * @author linfengqi
 * @since java 1.5
 * @date 2009-12-22
 */
public class HttpEncoder implements ProtocolEncoder {
	
	private static StringBuffer sb = new StringBuffer();
	private String delimiter;
	private static int contentLenghtOffset;
	private static int dateOffset;
	public String charset;
	private SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy hh:mm:ss 'GMT'");

	public HttpEncoder(String charset, LineDelimiter delimiter) {
		this.charset = charset;
		this.delimiter = delimiter.getValue();
		init();
	}
	
	private void init() {
		sb.append("HTTP/1.1 200 OK");
		sb.append(delimiter);
		sb.append("Content-Length: ");
		contentLenghtOffset = sb.length();
		sb.append(delimiter);
		sb.append("Server: GameServer/1.0");
		sb.append(delimiter);
		sb.append("Date: ");
		dateOffset = sb.length();
		sb.append(delimiter);
		sb.append("Content-Type: text/html");
		sb.append(delimiter);
		sb.append("Cache-control: private");
		sb.append(delimiter);
		sb.append("Connection: keep-alive");
		sb.append(delimiter);
		sb.append(delimiter);
	}

	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		if (message == null || !(message instanceof String)) return;
		String str = (String) message;
		sb.insert(dateOffset, format.format(new Date()));
		sb.insert(contentLenghtOffset, str.length());
		sb.append(str);
		sb.append(delimiter);
		sb.append(delimiter);
		IoBuffer buffer = IoBuffer.wrap(sb.toString().getBytes(charset));
		out.write(buffer);
	}
	
	public void dispose(IoSession session) throws Exception {
		// TODO Auto-generated method stub

	}
	

}
